
#include "server.h"

#define	BUFFSIZE 1024

/*功能：子线程程序，数据接受和存储
 *参数：clienfd:客户端文件描述符；pthread_args:子线程参数
 *返回：错误返回-1*/

void *pthread_work(void *args)
{
	sqlite3               	*db;
	char                 	receive_buff[BUFFSIZE];

	char                 	ID[50];
	char                 	temp[10];
	char                 	time[20];
	int			re_val = -1;
	char                 	finish[25]="serve receive finish!";

	pthread_args_t		*pthread_args = (pthread_args_t *)args;

	
	

	while(1) 
	{

		memset(receive_buff,0,sizeof(receive_buff));

		printf("starting to receive datas from client[%d] ...\n",pthread_args->clienfd);

		if((re_val=read(pthread_args->clienfd,receive_buff,sizeof(receive_buff))) < 0)
		{
			printf("read from client failed: %s\n",strerror(errno));
			datbas_close(db);
			pthread_exit(NULL);
			goto Cleanup;
	
		}

		else if(re_val == 0)
		{
			printf("Disconnect with client..\n");
			datbas_close(db);
			pthread_exit(NULL);
			goto Cleanup;

		}

		if(deal_data(receive_buff,ID,temp,time) < 0)
		{

			printf("deal_data failed:%s\n",strerror(errno));
			datbas_close(db);
			pthread_exit(NULL);
			goto Cleanup;

		}


		pthread_mutex_lock(&pthread_args->lock);//上锁

		datbas_open(&db);//打开数据库

		if(datbas_insert(db,ID,temp,time) < 0)
		{

			printf("datbas_insert failed:%s\n",strerror(errno));
			datbas_close(db);
			pthread_exit(NULL);
			goto Cleanup;

		}

		pthread_mutex_unlock(&pthread_args->lock);//解锁

		if(write(pthread_args->clienfd,finish,sizeof(finish))<0)
		{

			printf("write to client failed:%s\n",strerror(errno));
			goto Cleanup;
		}



	}

Cleanup:
		free(pthread_args);
}
